#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define N 2
#define NUM 30

void Write(int wfd){
    string s = "l like Linux!";
    pid_t pid = getpid();
    int number = 0;
    char buffer[NUM];
    while(true){
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d\n", s.c_str(), pid, number);
        //cout << buffer;
        number++;
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
    
}

void Read(int rfd){
    char buffer[NUM];
    while(true){
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0){
            buffer[n] = 0;
            cout << "father get a message[" << getpid() << "]# " << buffer;
        }
    }
}

int main(void){
    int pipefd[N] = {0};
    int pip = pipe(pipefd);
    if(pip == -1){
        perror("Create pipe failed!");
        exit(1);
    }
    // cout << "pipefd[0]:" << pipefd[0] << endl;
    // cout << "pipefd[1]:" << pipefd[1] << endl;
    pid_t id = fork();
    if(id == 0){
        //子进程->write
        close(pipefd[0]);
        //write(pipefd[1], "i like Linux!\n", 15);
        Write(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    else if(id > 0){
        //父进程->read
        //char buf[20];
        //read(pipefd[0], buf, 20);
        //cout << buf;
        close(pipefd[1]);
        Read(pipefd[0]);
        int status;
        wait(&status);
    }
    else{
        perror("fork faild!");
        exit(2);
    }
    return 0;
}